
package br.com.duduso.conferencia_claro_desktop.screens;

import br.com.duduso.conferencia_claro_desktop.components.FrameInterno;
import br.com.duduso.conferencia_claro_desktop.components.BarraProgresso;
import br.com.duduso.conferencia_claro_desktop.components.Mensagens;
import br.com.duduso.conferencia_claro_desktop.components.SelecaoArquivo;
import br.com.duduso.conferencia_claro_desktop.services.ConferenciasService;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author duduso
 */
public class TelaConferenciaClaro extends FrameInterno {

    private List<File> arquivosConferencia;
    private File arquivoTotal;
    private ConferenciasService service;
    private GUIPrincipal guiPrincipal;

    public TelaConferenciaClaro(GUIPrincipal gui) {
            initComponents();
            initValues();
            this.btRemover.setVisible(false);
            this.btAbrir.setVisible(false);
            this.btDetalhar.setVisible(false);
            this.guiPrincipal = gui;
    }

    private void initValues(){
            this.arquivosConferencia = new ArrayList<File>();
            this.arquivoTotal = null;
            this.service = new ConferenciasService();
            this.tabelaArquivos.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnConferencia = new javax.swing.JPanel();
        lbArquivoTotal = new javax.swing.JLabel();
        btFechar = new javax.swing.JButton();
        btArquivoTotal = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tabelaArquivos = new javax.swing.JTable();
        btRemover = new javax.swing.JButton();
        btAddArquivos = new javax.swing.JButton();
        lbTotal = new javax.swing.JLabel();
        btLimparCampos = new javax.swing.JButton();
        btConferir = new javax.swing.JButton();
        btAbrir = new javax.swing.JButton();
        btDetalhar = new javax.swing.JButton();

        setBackground(new java.awt.Color(193, 205, 205));
        setPreferredSize(new java.awt.Dimension(952, 564));

        pnConferencia.setBackground(new java.awt.Color(193, 205, 205));
        pnConferencia.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true), "CONFERÊNCIA DE CONTAS DA CLARO", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Arial", 1, 12))); // NOI18N

        lbArquivoTotal.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
        lbArquivoTotal.setText("<html><b>ARQUIVO DE TOTALIZAÇÃO: </b></html>");

        btFechar.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
        btFechar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/close.png"))); // NOI18N
        btFechar.setText("<html><b>Fechar</b></html>");
        btFechar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btFecharActionPerformed(evt);
            }
        });

        btArquivoTotal.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
        btArquivoTotal.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/excel.png"))); // NOI18N
        btArquivoTotal.setText("<html><b>Selecionar Arquivo...</b></html>");
        btArquivoTotal.setActionCommand("selecionar01");
        btArquivoTotal.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btArquivoTotalActionPerformed(evt);
            }
        });

        tabelaArquivos.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
        tabelaArquivos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "<html><b>Arquivos Selecionados</b></html>"
            }
        ));
        tabelaArquivos.getTableHeader().setReorderingAllowed(false);
        tabelaArquivos.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tabelaArquivosMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tabelaArquivos);

        btRemover.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
        btRemover.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/delete.png"))); // NOI18N
        btRemover.setText("<html><b>Remover</b></html>");
        btRemover.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btRemoverActionPerformed(evt);
            }
        });

        btAddArquivos.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
        btAddArquivos.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/excel.png"))); // NOI18N
        btAddArquivos.setText("<html><b>Add Arquivos</b></html>");
        btAddArquivos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btAddArquivosActionPerformed(evt);
            }
        });

        lbTotal.setFont(new java.awt.Font("Ubuntu", 1, 15));
        lbTotal.setForeground(new java.awt.Color(193, 25, 25));

        btLimparCampos.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
        btLimparCampos.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/clear.png"))); // NOI18N
        btLimparCampos.setText("<html><b>Limpar Campos</b></html>");
        btLimparCampos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btLimparCamposActionPerformed(evt);
            }
        });

        btConferir.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
        btConferir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/conferir.png"))); // NOI18N
        btConferir.setText("<html><b>Conferir</b></html>");
        btConferir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btConferirActionPerformed(evt);
            }
        });

        btAbrir.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
        btAbrir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/open.png"))); // NOI18N
        btAbrir.setText("<html><b>Abrir Conferência</b></html>");
        btAbrir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btAbrirActionPerformed(evt);
            }
        });

        btDetalhar.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
        btDetalhar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/detail.png"))); // NOI18N
        btDetalhar.setText("<html><b>Detalhar</b></html>"); // NOI18N
        btDetalhar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btDetalharActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout pnConferenciaLayout = new javax.swing.GroupLayout(pnConferencia);
        pnConferencia.setLayout(pnConferenciaLayout);
        pnConferenciaLayout.setHorizontalGroup(
            pnConferenciaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnConferenciaLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnConferenciaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(pnConferenciaLayout.createSequentialGroup()
                        .addComponent(lbArquivoTotal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lbTotal, javax.swing.GroupLayout.DEFAULT_SIZE, 565, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btArquivoTotal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 892, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnConferenciaLayout.createSequentialGroup()
                        .addComponent(btAddArquivos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btRemover, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btFechar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 189, Short.MAX_VALUE)
                        .addComponent(btDetalhar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btAbrir, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btConferir, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btLimparCampos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        pnConferenciaLayout.setVerticalGroup(
            pnConferenciaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnConferenciaLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnConferenciaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbArquivoTotal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btArquivoTotal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lbTotal))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(pnConferenciaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btAddArquivos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btRemover, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btLimparCampos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btFechar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btConferir, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btAbrir, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btDetalhar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(243, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(pnConferencia, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(pnConferencia, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btFecharActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btFecharActionPerformed
        fecharTab();
}//GEN-LAST:event_btFecharActionPerformed

    private void btArquivoTotalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btArquivoTotalActionPerformed
        exibirJanelaSelecaoArquivos(true);
}//GEN-LAST:event_btArquivoTotalActionPerformed

    private void tabelaArquivosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tabelaArquivosMouseClicked
        isBotaoRemoverVisivel();
}//GEN-LAST:event_tabelaArquivosMouseClicked

    private void btRemoverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btRemoverActionPerformed
        removerLinhaTabela();
}//GEN-LAST:event_btRemoverActionPerformed

    private void btAddArquivosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btAddArquivosActionPerformed
        exibirJanelaSelecaoArquivos(false);
}//GEN-LAST:event_btAddArquivosActionPerformed

    private void btLimparCamposActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btLimparCamposActionPerformed
        limparCampos();
}//GEN-LAST:event_btLimparCamposActionPerformed

    private void btConferirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btConferirActionPerformed
        gerarConferencia();
}//GEN-LAST:event_btConferirActionPerformed

    private void btAbrirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btAbrirActionPerformed
        service.abrirArquivoSaida();
}//GEN-LAST:event_btAbrirActionPerformed

    private void btDetalharActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btDetalharActionPerformed
        guiPrincipal.adicionarTab(Mensagens.getInstance().getMessage("tituloAbaDetalhesConferencia"),
                new TelaDetalhesContatos(arquivoTotal, service, arquivosConferencia));
}//GEN-LAST:event_btDetalharActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btAbrir;
    private javax.swing.JButton btAddArquivos;
    private javax.swing.JButton btArquivoTotal;
    private javax.swing.JButton btConferir;
    private javax.swing.JButton btDetalhar;
    private javax.swing.JButton btFechar;
    private javax.swing.JButton btLimparCampos;
    private javax.swing.JButton btRemover;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lbArquivoTotal;
    private javax.swing.JLabel lbTotal;
    private javax.swing.JPanel pnConferencia;
    private javax.swing.JTable tabelaArquivos;
    // End of variables declaration//GEN-END:variables

    private void exibirJanelaSelecaoArquivos(boolean isArquivoTotal){
            File arquivo = SelecaoArquivo.getInstance(".xls").selecionarArquivo();
            if (arquivo == null) {
                    return;
            }else if(isArquivoTotal && isOperacaoValida(arquivo, true)){
                    this.arquivoTotal = arquivo;
                    configurarValorInputArquivoTotal(arquivoTotal);
                    this.btDetalhar.setVisible(true);
            }else {
                    addConteudoTabela(arquivo);
            }
    }

    private void configurarValorInputArquivoTotal(File arquivoEntrada){
            if(arquivoEntrada != null){
                    this.lbTotal.setText(arquivoEntrada.getName());
            }else{
                    this.lbTotal.setText(null);
            }
    }

    private void addConteudoTabela(File arquivoEntrada){
            if(isOperacaoValida(arquivoEntrada, false)){
                    DefaultTableModel dtm = (DefaultTableModel) tabelaArquivos.getModel();
                    dtm.addRow(new Object[]{arquivoEntrada.getName()});
                    this.tabelaArquivos.setModel(dtm);
                    this.arquivosConferencia.add(arquivoEntrada);
            }
    }

    private void isBotaoRemoverVisivel(){
            btRemover.setVisible(tabelaArquivos.getSelectedRow() > -1);
    }

    private void removerLinhaTabela(){
            int linhaSelecionada = tabelaArquivos.getSelectedRow();
            ((DefaultTableModel)tabelaArquivos.getModel()).removeRow(linhaSelecionada);
            this.arquivosConferencia.remove(linhaSelecionada);
            isBotaoRemoverVisivel();
    }

    private void limparCampos(){
            limparTabela();
            this.arquivoTotal = null;
            this.lbTotal.setText(null);
            this.arquivosConferencia.clear();
            this.btAbrir.setVisible(false);
            this.btDetalhar.setVisible(false);
            this.btConferir.setVisible(true);
    }

    private void limparTabela(){
            for(int i = tabelaArquivos.getRowCount(); i >= 1; i--){
                    ((DefaultTableModel)tabelaArquivos.getModel()).removeRow(i - 1);
            }
    }

    private boolean isOperacaoValida(File arquivoEntrada, boolean isValidacaoArquivoTotal){
            if(arquivosConferencia.contains(arquivoEntrada)
                    || (!isValidacaoArquivoTotal && arquivoTotal != null && arquivoEntrada.equals(arquivoTotal))){
                    Mensagens.getInstance().exibirMensagemErro(null, "msgArquivoJaAdicionado");
                    return false;
            }else if(!arquivoEntrada.getPath().endsWith(".xls")){
                    Mensagens.getInstance().exibirMensagemErro(null, "msgFormatoArquivoInvalido");
                    return false;
            }
            return true;
    }

    private void gerarConferencia(){
            if(arquivoTotal == null || arquivosConferencia.isEmpty()){
                    Mensagens.getInstance().exibirMensagemErro(null, "msgArquivosEscolhidos");
            }else{
                    new BarraProgresso() {
                            @Override
                            public void executar() {
                                    try {
                                            service.processarArquivosEntrada(arquivosConferencia, arquivoTotal);
                                            Mensagens.getInstance().exibirMensagemInformacao(null, "msgSucessoConferencia");
                                            limparCampos();
                                            btAbrir.setVisible(true);
                                            btConferir.setVisible(false);
                                    } catch (Exception ex) {
                                            JOptionPane.showMessageDialog(null, ex);
                                    }
                            }
                    };
            }
    }

}
